package com.luoran.system.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Aspect
@Slf4j
public class MyLogAspect {

    private static final Logger logger = LoggerFactory.getLogger(MyLogAspect.class);

    @Pointcut("@annotation(com.luoran.system.aop.MyLogAnn)")
    public void logPointcut(){}

    @Around("logPointcut()")
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result;
        try {
            logger.info("开始执行方法：{}，描述：{}", joinPoint.getSignature().toShortString(), getAnnotationDescription(joinPoint));
            result = joinPoint.proceed();
            return result;
        } finally {
            long endTime = System.currentTimeMillis();
            long duration = endTime - startTime;
            logger.info("方法执行结束：{}，耗时：{} 毫秒", joinPoint.getSignature().toShortString(), duration);
        }
    }

    private String getAnnotationDescription(JoinPoint joinPoint) throws NoSuchMethodException {
        MyLogAnn annotation = joinPoint.getTarget().getClass().getMethod(joinPoint.getSignature().getName()).getAnnotation(MyLogAnn.class);
        return annotation!= null? annotation.description() : "";
    }

}
